<?php


namespace app\base\service;

use think\admin\service\AdminService;
use WebSocket\Client;
use think\Cache;

/**
 * websocket消息发送服务
 * Class AdminService
 * @package think\admin\service
 */
class WsSendService extends AdminService
{
    /**
     * 发送消息
     */
    public function send($device_id,$type,$data=[])
    {
        $msg = [];
        switch ($type){
            //执行任务
            case 1:
                $msg = [
                    'action'=>"service",
                    'target_device'=>$device_id,
//                    'content'=>[
//                        'type'=>1,
//                        'script_file'=>"upload1.js",
//                        'data_id'=>214,
//                        'is_update'=>1
//                    ],
                    'content'=>$data,
                ];
                break;
            //执行脚本更新
            case 2:
                $msg = [
                    'action'=>"service",
                    'target_device'=>$device_id,
                    'content'=>[
                        'type'=>2,
                        'data'=>$data,
                    ],
                ];
                break;

        }
       if($msg){
           try {
               // 连接WebSocket服务器
               $client = new Client("ws://127.0.0.1:7879");
               // 发送消息
               $client->send(json_encode($msg));

               // 关闭连接
               $client->close();
               return true;
           } catch (Exception $e) {
               $this->app->log->error("推送失败_{$device_id}：{$e->getMessage()}");
               return $e->getMessage();
           }
       }
       return false;

    }

}
